/// <reference path="3rd/jquery.d.ts" />
/// <reference path="3rd/doT.d.ts" />

/// <reference path="3rd/doT.d.ts" />
/// <reference path="3rd/chrome.d.ts" />
/// <reference path="3rd/less.d.ts" />

/// <reference path="settings.ts" />


// Interface
interface IBackground {
}

// Module
module pages {

    // Class
    export class Background implements IBackground {
        constructor () {
            window.addEventListener('message', (e: any) =>{
                this.Print(e);
                console.log("window.addEventListener");
            });
            chrome.extension.onMessage.addListener((request, sender, sendResponse) => {
                this.Recieve(request, sender, sendResponse);
                console.log("chrome.extension.onMessage.addListener");

            });
        }

        private Print(event) {
            if (event.data.html) {
                var docprint = window.open("", "", "toolbar=yes, location=no, directories=yes, menubar=yes, scrollbars=yes, left=100, top=25");
                docprint.document.open();
                docprint.document.write('<html><head>');

                var cardCss = chrome.extension.getURL('styles/print.min.css');
                var jquery = chrome.extension.getURL('scripts/3rd/impl/jquery-1.8.2.min.js');
                docprint.document.write('<link rel="stylesheet" type="text/css" href="' + cardCss + '" />');
                docprint.document.write('<script src="' + jquery + '" ></script>');

                var parser = new less.Parser();
                parser.parse(core.Settings.instance.css, function (err, tree) {
                    docprint.document.write('<style>' + tree.toCSS() + '</style>');
                    docprint.document.write('</head><body onLoad="self.print()">');
                    docprint.document.write(event.data.html);
                    docprint.document.write('</body></html>');
                    docprint.document.close();
                    docprint.focus();
                });
            }
        }

        private Recieve(request, sender, sendResponse) {
            var sandbox = <any>document.getElementById('sandbox');
            var data = request.data;
            data.settings = {};
            data.settings.project = core.Settings.instance.project;
            data.settings.template = core.Settings.instance.template;
            data.settings.func = core.Settings.instance.itemfunction;
            var message = {
                command: 'render',
                context: data
            };
            sandbox.contentWindow.postMessage(message, '*');
            sendResponse();

        }
    }
}

